import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  List,
  ListItem,
  ListItemText,
  Drawer,
  IconButton,
  useTheme,
  useMediaQuery,
  ListItemButton,
  Avatar,
  Divider,
  CircularProgress,
  Tooltip,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Select,
  FormControl,
  InputLabel,
  SelectChangeEvent,
} from '@mui/material';
import {
  Send as SendIcon,
  Menu as MenuIcon,
  AddCircleOutline as NewChatIcon,
  AccountCircle as UserIcon,
  SmartToy as BotIcon,
  Delete as DeleteIcon,
  MoreVert as MoreIcon,
  ExitToApp as LogoutIcon,
  People as PeopleIcon,
  CloudUpload as UploadIcon,
  Search as SearchIcon,
} from '@mui/icons-material';
import { chat, auth } from '../services/api';
import { useNavigate } from 'react-router-dom';
import { useUser } from '../contexts/UserContext';

// 添加模型枚举类型
enum Model {
  MODEL_1 = 'model_1',
  MODEL_2 = 'model_2',
  MODEL_3 = 'model_3',
}

// 模型名称映射
const modelNames: Record<Model, string> = {
  [Model.MODEL_1]: '模型一',
  [Model.MODEL_2]: '模型二',
  [Model.MODEL_3]: '模型三',
};

interface Message {
  id: number;
  content: string;
  is_user: boolean;
  created_at: string;
}

interface Conversation {
  conversation_id: string;
  last_message_time: string;
  last_message_content?: string;
}

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
}

const Chat: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [currentConversation, setCurrentConversation] = useState<string | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [contextMenu, setContextMenu] = useState<{
    mouseX: number;
    mouseY: number;
    conversationId: string;
  } | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [conversationToDelete, setConversationToDelete] = useState<string | null>(null);
  // 添加模型选择状态
  const [selectedModel, setSelectedModel] = useState<Model>(Model.MODEL_1);
  
  // 使用UserContext获取用户信息
  const { currentUser } = useUser();
  
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const inputRef = useRef<HTMLInputElement>(null);
  const navigate = useNavigate();

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    loadConversations();
  }, []);

  useEffect(() => {
    if (currentConversation) {
      loadMessages(currentConversation);
    }
  }, [currentConversation]);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 聚焦输入框
  useEffect(() => {
    if (!isMobile) {
      inputRef.current?.focus();
    }
  }, [currentConversation, isMobile]);

  const loadConversations = async () => {
    try {
      setLoading(true);
      const response = await chat.getConversations();
      // 按照最后一条消息时间排序，最新的在前面
      const sortedConversations = response.data.sort((a: Conversation, b: Conversation) => {
        return new Date(b.last_message_time).getTime() - new Date(a.last_message_time).getTime();
      });
      setConversations(sortedConversations);
    } catch (error) {
      console.error('加载对话列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadMessages = async (conversationId: string) => {
    try {
      setLoading(true);
      const response = await chat.getMessages(conversationId);
      setMessages(response.data);
    } catch (error) {
      console.error('加载消息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const deleteConversation = async (conversationId: string) => {
    try {
      setLoading(true);
      await chat.deleteConversation(conversationId);
      
      // 从对话列表中移除被删除的对话
      setConversations(prev => prev.filter(conv => conv.conversation_id !== conversationId));
      
      // 如果当前正在查看的对话被删除，则切换到新对话
      if (currentConversation === conversationId) {
        setCurrentConversation(null);
        setMessages([]);
      }
      
    } catch (error) {
      console.error('删除对话失败:', error);
    } finally {
      setLoading(false);
      setDeleteDialogOpen(false);
      setConversationToDelete(null);
    }
  };

  const handleSend = async () => {
    if (!input.trim() || loading) return;

    const userMessage = input;
    setInput('');
    setLoading(true);

    // 立即显示用户消息
    const tempUserMsg: Message = {
      id: Date.now(),
      content: userMessage,
      is_user: true,
      created_at: new Date().toISOString()
    };
    
    setMessages(prev => [...prev, tempUserMsg]);

    try {
      const response = await chat.sendMessage({
        content: userMessage,
        conversation_id: currentConversation || undefined,
        model: selectedModel, // 添加模型参数
      });
      
      if (!currentConversation) {
        setCurrentConversation(response.data.conversation_id);
      }
      
      // 移除临时消息，添加服务器返回的消息
      setMessages(prev => {
        const filtered = prev.filter(msg => msg.id !== tempUserMsg.id);
        return [...filtered, ...response.data.messages];
      });
      
      await loadConversations();
    } catch (error) {
      console.error('发送消息失败:', error);
      // 添加错误提示
      setMessages(prev => [
        ...prev, 
        {
          id: Date.now() + 1,
          content: '消息发送失败，请重试。',
          is_user: false,
          created_at: new Date().toISOString()
        }
      ]);
    } finally {
      setLoading(false);
      inputRef.current?.focus();
    }
  };

  // 处理模型选择变更
  const handleModelChange = (event: SelectChangeEvent) => {
    setSelectedModel(event.target.value as Model);
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const startNewChat = () => {
    setCurrentConversation(null);
    setMessages([]);
    setDrawerOpen(false);
    inputRef.current?.focus();
  };

  const handleContextMenu = (
    event: React.MouseEvent,
    conversationId: string
  ) => {
    event.preventDefault();
    event.stopPropagation();
    setContextMenu({
      mouseX: event.clientX,
      mouseY: event.clientY,
      conversationId,
    });
  };

  const handleDeleteClick = (conversationId: string) => {
    setConversationToDelete(conversationId);
    setDeleteDialogOpen(true);
    setContextMenu(null);
  };

  // 格式化消息内容，支持换行
  const formatMessageContent = (content: string) => {
    return content.split('\n').map((line, i) => (
      <React.Fragment key={i}>
        {line}
        {i < content.split('\n').length - 1 && <br />}
      </React.Fragment>
    ));
  };

  // 截取对话内容
  const truncateMessage = (content: string, maxLength: number = 30) => {
    if (!content) return '';
    return content.length > maxLength
      ? content.substring(0, maxLength) + '...'
      : content;
  };

  // 获取对话的第一条消息作为标题
  const getConversationTitle = (conversationId: string) => {
    const conversation = conversations.find(c => c.conversation_id === conversationId);
    if (conversation && conversation.last_message_content) {
      return truncateMessage(conversation.last_message_content);
    }
    return `对话 ${conversationId.slice(0, 6)}...`;
  };

  // 获取对话日期显示
  const getFormattedDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const isToday = date.toDateString() === now.toDateString();
    
    if (isToday) {
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      });
    }
    
    const isThisYear = date.getFullYear() === now.getFullYear();
    if (isThisYear) {
      return date.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric'
      });
    }
    
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    window.location.href = '/login';
  };

  // 导航到不同页面
  const navigateTo = (path: string) => {
    navigate(path);
  };

  const drawerContent = (
    <Box 
      sx={{ 
        width: 280, 
        height: '100%', 
        display: 'flex', 
        flexDirection: 'column',
        bgcolor: theme.palette.background.default
      }}
    >
      <Box 
        sx={{ 
          p: 2, 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          borderBottom: `1px solid ${theme.palette.divider}`
        }}
      >
        <Typography variant="h6" fontWeight="500">
          对话摘要列表
        </Typography>
      </Box>

      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          px: 1.5,
          py: 1.25,
          borderBottom: `1px solid ${theme.palette.divider}`,
          bgcolor: theme.palette.background.default,
          cursor: 'pointer',
          '&:hover': {
            backgroundColor: 'rgba(0, 0, 0, 0.04)'
          }
        }}
        onClick={startNewChat}
      >
        <NewChatIcon sx={{ color: theme.palette.primary.main }} />
        <Typography 
          variant="subtitle1" 
          sx={{ 
            ml: 1.5,
            fontWeight: 500,
            fontSize: '0.95rem',
            color: theme.palette.primary.main
          }}
        >
          开始生成新摘要
        </Typography>
      </Box>

      <Box sx={{ flexGrow: 1, overflow: 'auto' }}>
        <List sx={{ p: 1 }}>
          {conversations.length === 0 ? (
            <ListItem>
              <ListItemText 
                primary="暂无对话摘要历史" 
                secondary="开始生成新的对话摘要吧" 
                primaryTypographyProps={{ color: 'text.secondary' }}
                secondaryTypographyProps={{ color: 'text.disabled' }}
              />
            </ListItem>
          ) : (
            conversations.map((conv) => (
              <ListItem 
                key={conv.conversation_id} 
                disablePadding
                sx={{ mb: 0.5 }}
                onContextMenu={(e) => handleContextMenu(e, conv.conversation_id)}
              >
                <ListItemButton
                  selected={currentConversation === conv.conversation_id}
                  onClick={() => {
                    setCurrentConversation(conv.conversation_id);
                    setDrawerOpen(false);
                  }}
                  sx={{ 
                    borderRadius: 1.5,
                    py: 1,
                    pr: 1,
                    '&.Mui-selected': {
                      backgroundColor: 'rgba(16, 163, 127, 0.1)',
                      '&:hover': {
                        backgroundColor: 'rgba(16, 163, 127, 0.15)',
                      }
                    }
                  }}
                >
                  <ListItemText
                    primary={getConversationTitle(conv.conversation_id)}
                    secondary={getFormattedDate(conv.last_message_time)}
                    primaryTypographyProps={{
                      noWrap: true,
                      fontWeight: currentConversation === conv.conversation_id ? 500 : 400
                    }}
                    secondaryTypographyProps={{
                      noWrap: true,
                      fontSize: '0.75rem'
                    }}
                    sx={{ flex: 1, minWidth: 0 }}
                  />
                  <IconButton
                    size="small"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteClick(conv.conversation_id);
                    }}
                    sx={{ 
                      opacity: 0.5,
                      '&:hover': { opacity: 1 }
                    }}
                  >
                    <DeleteIcon fontSize="small" />
                  </IconButton>
                </ListItemButton>
              </ListItem>
            ))
          )}
        </List>
      </Box>

      {/* 用户信息区域 */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          py: 1.5,
          px: 2,
          borderTop: `1px solid ${theme.palette.divider}`,
          bgcolor: theme.palette.background.default,
          height: '64px',
          boxSizing: 'border-box'
        }}
      >
        <Avatar
          sx={{
            bgcolor: 'primary.main',
            width: 40,
            height: 40
          }}
        >
          {currentUser?.username.charAt(0).toUpperCase() || <UserIcon />}
        </Avatar>
        <Box sx={{ ml: 1.5, overflow: 'hidden' }}>
          <Typography
            variant="subtitle2"
            sx={{
              fontWeight: 500,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap'
            }}
          >
            {currentUser?.username || '用户名'}
          </Typography>
          <Typography
            variant="caption"
            sx={{
              color: 'text.secondary',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              display: 'block'
            }}
          >
            {currentUser?.email || '邮箱'}
          </Typography>
        </Box>
        <Box sx={{ ml: 'auto' }}>
          <Tooltip title="退出登录">
            <IconButton
              onClick={handleLogout}
              size="small"
              sx={{ color: 'text.secondary' }}
            >
              <LogoutIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      </Box>
    </Box>
  );

  return (
    <Box 
      sx={{ 
        display: 'flex', 
        height: '100vh',
        bgcolor: theme.palette.background.default
      }}
    >
      {/* 侧边栏（桌面端固定显示） */}
      {!isMobile && (
        <Box 
          sx={{ 
            width: 280, 
            borderRight: `1px solid ${theme.palette.divider}`,
            display: 'flex',
            flexDirection: 'column'
          }}
        >
          {drawerContent}
        </Box>
      )}

      {/* 侧边栏（移动端抽屉） */}
      <Drawer
        anchor="left"
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        sx={{
          '& .MuiDrawer-paper': {
            boxSizing: 'border-box',
            width: 280,
          },
        }}
      >
        {drawerContent}
      </Drawer>

      {/* 主聊天区域 */}
      <Box 
        sx={{ 
          flex: 1, 
          display: 'flex', 
          flexDirection: 'column',
          height: '100vh',
          position: 'relative'
        }}
      >
        {/* 顶部栏 */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            p: 2,
            backgroundColor: theme.palette.background.paper,
          }}
        >
          {isMobile && (
            <IconButton 
              onClick={() => setDrawerOpen(true)}
              edge="start"
              sx={{ mr: 1 }}
            >
              <MenuIcon />
            </IconButton>
          )}
          <Box sx={{ display: 'flex', alignItems: 'center', flexGrow: 1 }}>
            <FormControl 
              variant="standard" 
              size="small"
              sx={{ minWidth: 120 }}
            >
              <Select
                value={selectedModel}
                onChange={handleModelChange}
                disableUnderline
                sx={{ 
                  fontSize: '0.95rem',
                  fontWeight: 500,
                  color: theme.palette.text.primary,
                  '& .MuiSelect-select': { 
                    py: 0.5,
                    '&:focus': {
                      backgroundColor: 'transparent',
                    }
                  },
                  '& .MuiSelect-icon': {
                    color: theme.palette.text.secondary,
                  }
                }}
              >
                <MenuItem value={Model.MODEL_1}>{modelNames[Model.MODEL_1]}</MenuItem>
                <MenuItem value={Model.MODEL_2}>{modelNames[Model.MODEL_2]}</MenuItem>
                <MenuItem value={Model.MODEL_3}>{modelNames[Model.MODEL_3]}</MenuItem>
              </Select>
            </FormControl>
          </Box>
          
          {/* 功能菜单区 */}
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            {currentConversation && (
              <Tooltip title="删除对话">
                <IconButton 
                  onClick={() => handleDeleteClick(currentConversation)}
                  sx={{ mx: 0.5 }}
                >
                  <DeleteIcon />
                </IconButton>
              </Tooltip>
            )}
            
            {/* 仅管理员可见的用户管理按钮 */}
            {currentUser?.role === 'admin' && (
              <Tooltip title="用户管理">
                <IconButton 
                  onClick={() => navigateTo('/user-management')}
                  sx={{ mx: 0.5 }}
                >
                  <PeopleIcon />
                </IconButton>
              </Tooltip>
            )}
            
            <Tooltip title="数据上传">
              <IconButton 
                onClick={() => navigateTo('/data-upload')}
                sx={{ mx: 0.5 }}
              >
                <UploadIcon />
              </IconButton>
            </Tooltip>
            
            {/* 摘要查询按钮，所有用户可见 */}
            <Tooltip title="摘要查询">
              <IconButton 
                onClick={() => navigateTo('/summary-search')}
                sx={{ mx: 0.5 }}
              >
                <SearchIcon />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>

        {/* 消息区域 */}
        <Box 
          sx={{ 
            flex: 1, 
            overflowY: 'auto',
            p: 2,
            display: 'flex',
            flexDirection: 'column',
            backgroundColor: theme.palette.background.paper,
          }}
        >
          {messages.length === 0 ? (
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                height: '100%',
                color: 'text.secondary',
                textAlign: 'center',
                p: 3,
              }}
            >
              <BotIcon sx={{ fontSize: 64, color: 'primary.main', mb: 2, opacity: 0.8 }} />
              <Typography variant="h5" gutterBottom>
                欢迎使用对话摘要生成系统
              </Typography>
              <Typography variant="body1" color="text.secondary" sx={{ maxWidth: 500 }}>
                请输入您的对话文本，如：<br></br>
                人名1:说话内容<br></br>
                人名2:说话内容<br></br>
              </Typography>
            </Box>
          ) : (
            messages.map((message) => (
              <Box
                key={message.id}
                sx={{
                  display: 'flex',
                  mb: 3,
                  alignItems: 'flex-start',
                  flexDirection: message.is_user ? 'row-reverse' : 'row',
                }}
              >
                <Avatar
                  sx={{
                    bgcolor: message.is_user ? 'primary.main' : 'secondary.light',
                    mr: message.is_user ? 0 : 2,
                    ml: message.is_user ? 2 : 0,
                  }}
                >
                  {message.is_user ? <UserIcon /> : <BotIcon />}
                </Avatar>
                <Box
                  sx={{
                    maxWidth: {
                      xs: '75%',
                      sm: '70%',
                      md: '65%',
                    },
                  }}
                >
                  <Paper
                    elevation={0}
                    sx={{
                      p: 2,
                      bgcolor: message.is_user 
                        ? 'primary.main' 
                        : theme.palette.background.paper,
                      color: message.is_user ? 'white' : 'text.primary',
                      borderRadius: 2,
                      position: 'relative',
                    }}
                  >
                    <Typography 
                      variant="body1" 
                      component="div"
                      sx={{ 
                        whiteSpace: 'pre-wrap',
                        wordBreak: 'break-word', 
                      }}
                    >
                      {formatMessageContent(message.content)}
                    </Typography>
                  </Paper>
                  <Typography 
                    variant="caption" 
                    sx={{ 
                      display: 'block', 
                      textAlign: message.is_user ? 'right' : 'left',
                      mt: 0.5,
                      color: 'text.disabled',
                      fontSize: '0.7rem'
                    }}
                  >
                    {new Date(message.created_at).toLocaleString('zh-CN', {
                      hour: '2-digit',
                      minute: '2-digit'
                    })}
                  </Typography>
                </Box>
              </Box>
            ))
          )}
          {loading && (
            <Box 
              sx={{ 
                display: 'flex', 
                alignItems: 'center', 
                mb: 3 
              }}
            >
              <Avatar sx={{ bgcolor: 'secondary.light', mr: 2 }}>
                <BotIcon />
              </Avatar>
              <CircularProgress size={24} color="inherit" sx={{ ml: 1 }} />
            </Box>
          )}
          <div ref={messagesEndRef} />
        </Box>

        {/* 输入区域 */}
        <Box
          sx={{
            py: 1.5,
            px: 2,
            borderTop: `1px solid ${theme.palette.divider}`,
            backgroundColor: theme.palette.background.paper,
            display: 'flex',
            alignItems: 'center',
            boxSizing: 'border-box',
            height: '64px' // 精确匹配用户信息区域高度
          }}
        >
          <Box
            component="form"
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              maxWidth: '900px',
              width: '100%',
              mx: 'auto',
            }}
            onSubmit={(e) => {
              e.preventDefault();
              handleSend();
            }}
          >
            <TextField
              fullWidth
              multiline
              inputRef={inputRef}
              maxRows={1}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder="输入消息..."
              variant="outlined"
              sx={{
                '& .MuiOutlinedInput-root': {
                  borderRadius: 3,
                  fontSize: '0.95rem',
                  padding: '6px 14px',
                  height: '40px',
                  boxSizing: 'border-box'
                }
              }}
              disabled={loading}
            />
            <Tooltip title="发送消息">
              <Button
                variant="contained"
                color="primary"
                disabled={!input.trim() || loading}
                type="submit"
                sx={{
                  borderRadius: '50%',
                  minWidth: 'auto',
                  width: 40,
                  height: 40,
                  p: 0,
                }}
              >
                <SendIcon />
              </Button>
            </Tooltip>
          </Box>
        </Box>
      </Box>

      {/* 右键菜单 */}
      <Menu
        open={contextMenu !== null}
        onClose={() => setContextMenu(null)}
        anchorReference="anchorPosition"
        anchorPosition={
          contextMenu !== null
            ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
            : undefined
        }
      >
        <MenuItem 
          onClick={() => {
            if (contextMenu) {
              handleDeleteClick(contextMenu.conversationId);
            }
          }}
          sx={{ color: 'error.main' }}
        >
          <DeleteIcon fontSize="small" sx={{ mr: 1 }} />
          删除对话
        </MenuItem>
      </Menu>

      {/* 删除对话确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>删除对话</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除该对话吗？此操作无法撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button 
            onClick={() => {
              if (conversationToDelete) {
                deleteConversation(conversationToDelete);
              }
            }} 
            color="error" 
            autoFocus
          >
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Chat; 